package com.aida.evil.eda.Welcome;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Parcelable;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;

import com.aida.evil.aida.R;
import com.aida.evil.eda.Data.NetworkData;
import com.aida.evil.eda.Data.UserData;
import com.aida.evil.eda.EasyPermission.PermissionUtil;
import com.aida.evil.eda.EasyPermission.callback.PermissionResultCallBack;
import com.aida.evil.eda.Login.Login;
import com.aida.evil.eda.Toast.CustomSuperActivityToast;
import com.aida.evil.eda.Update.UpdateDownload;
import com.aida.evil.eda.Volley.VolleyHandler;
import com.aida.evil.eda.Volley.VolleyHttpRequest;
import com.aida.evil.eda.Window.CustomDialog;
import com.github.johnpersano.supertoasts.SuperActivityToast;
import com.github.johnpersano.supertoasts.SuperToast;
import com.github.johnpersano.supertoasts.util.OnClickWrapper;
import com.squareup.picasso.Picasso;

/****************************************************
 * Welcome
 * 作者：白雨濃  evil
 * 时间：16-2-9 12:13
 * 邮箱：evilbai@foxmail.com
 * 页面用途：欢迎界面，包含上部分的广告图片，下部分动画
 ****************************************************/
public class Welcome extends UpdateDownload
{
    private final static String UPDATEURL = "http://" + NetworkData.ServiceIP + "/Version?";
    private final static String IMGURL = "http://" + NetworkData.ServiceIP + "/EdaItem_Img?ItemImg=";

    private int versionCode;/*版本号*/

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.welcome);

        /*加载首页广告*/
        Picasso.with(this).load(IMGURL + "welcome.jpg").placeholder(R.mipmap.welcome_loading).into((ImageView) findViewById(R.id.welcome_img));
        /*加载底部图片*/
        Picasso.with(this).load(R.mipmap.welcome_bottom).into((ImageView) findViewById(R.id.welcome_bottom));

        getIMEI();
    }

    /**
     * 获取imei,在android 6.0涉及到权限问题
     * 检测升级包含在其中,获得imei后才能检测升级
     */
    private void getIMEI()
    {
        /**
         * 获取android6.0 IMEI
         */
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M)
        {
            PermissionUtil.getInstance().request(Welcome.this
                    , new String[]{Manifest.permission.READ_PHONE_STATE
                            , Manifest.permission.WRITE_EXTERNAL_STORAGE}
                    , new PermissionResultCallBack()
                    {
                        /*全部权限允许时调用*/
                        @Override
                        public void onPermissionGranted()
                        {
                            UserData.DATA_IMEI = ((TelephonyManager) Welcome.this.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
                            update();//检测软件升级
                        }

                        /*显示允许的权限*/
                        @Override
                        public void onPermissionGranted(String... strings)
                        {

                        }

                        /*未知*/
                        @Override
                        public void onPermissionDenied(String... strings)
                        {

                        }

                        /*显示禁止权限*/
                        @Override
                        public void onRationalShow(String... strings)
                        {
                            final CustomDialog.Builder builder = new CustomDialog.Builder(Welcome.this);
                            builder.setTitle("提示");
                            builder.setMessage("请允许权限,否则软件将不能够正常运行,您将不能够获得流量!\n请重启Eda易答,重新获取权限");
                            builder.setCanceledOnTouchOutside(false);
                            builder.setBackPressed(false);
                            builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
                            {
                                @Override
                                public void onClick(DialogInterface dialog, int which)
                                {
                                    builder.dismiss();
                                    finish();
                                }
                            });
                            builder.show();
                        }
                    });
        }
        else
        {
            UserData.DATA_IMEI = ((TelephonyManager) Welcome.this.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
            update();//检测软件升级
        }

    }


    /**
     * 用于检测软件升级
     * 上传用户数据包含在其中
     */
    private void update()
    {
        /*获取当前版本号*/
        // 获取packagemanager的实例
        PackageManager packageManager = getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = null;
        try
        {
            packInfo = packageManager.getPackageInfo(getPackageName(), 0);
        }
        catch (PackageManager.NameNotFoundException e)
        {
            e.printStackTrace();
        }
        versionCode = packInfo.versionCode;

        /*获取网络上的版本号*/
        VolleyHandler<String> stringVolleyHandler = new VolleyHandler<String>()
        {
            @Override
            public void reqSuccess(String response)
            {
                int net_versionCode = Integer.valueOf(response);
                //如果服务器的版本大于当前版本，进行更新
                if (net_versionCode > versionCode)
                {
                    downloadDecideNet(getNetworkType());
                    //接收下载完成后的广播
                    completeReceiver = new CompleteReceiver();
                    /** register download success broadcast **/
                    registerReceiver(completeReceiver,
                            new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
                }
                else
                {
                    /*检测升级成功后,进行初始化*/
                    startAnimation();
                }
            }

            @Override
            public void reqError(String error)
            {
                CustomSuperActivityToast.makeText(Welcome.this, "网络连接失败，是否检查网络设置或重试！", "重试", new
                        SuperToast.OnClickListener()
                        {
                            @Override
                            public void onClick(View view, Parcelable token)
                            {
                                update();
                            }
                        }).setDuration(Integer.MAX_VALUE)
                        .setBackground(SuperToast.Background.RED)
                        .show();
            }
        };

        VolleyHttpRequest.String_request(UPDATEURL, stringVolleyHandler);
    }

    /**
     * 设置欢迎界面底部彩虹动画
     *
     * @translateAnimation_end 最后完成的动画，用于监听动画结束，结束后进行intent隐式跳转到MainActivity
     * @translateAnimation 其他六项动画
     */
    private void startAnimation()
    {

        TranslateAnimation translateAnimation_end = new TranslateAnimation(0, 0, 390, 0);
        translateAnimation_end.setDuration(3800);
        findViewById(R.id.Welcome_7color_1).startAnimation(translateAnimation_end);

        TranslateAnimation translateAnimation = new TranslateAnimation(0, 0, 390, 0);
        translateAnimation.setDuration(3500);
        findViewById(R.id.Welcome_7color_2).startAnimation(translateAnimation);
        translateAnimation = new TranslateAnimation(0, 0, 390, 0);
        translateAnimation.setDuration(3100);
        findViewById(R.id.Welcome_7color_3).startAnimation(translateAnimation);
        translateAnimation = new TranslateAnimation(0, 0, 390, 0);
        translateAnimation.setDuration(2600);
        findViewById(R.id.Welcome_7color_4).startAnimation(translateAnimation);
        translateAnimation = new TranslateAnimation(0, 0, 390, 0);
        translateAnimation.setDuration(2200);
        findViewById(R.id.Welcome_7color_5).startAnimation(translateAnimation);
        translateAnimation = new TranslateAnimation(0, 0, 390, 0);
        translateAnimation.setDuration(1800);
        findViewById(R.id.Welcome_7color_6).startAnimation(translateAnimation);
        translateAnimation = new TranslateAnimation(0, 0, 390, 0);
        translateAnimation.setDuration(1500);
        findViewById(R.id.Welcome_7color_7).startAnimation(translateAnimation);

        translateAnimation_end.setAnimationListener(new Animation.AnimationListener()
        {
            @Override
            public void onAnimationStart(Animation animation)
            {

            }

            @Override
            public void onAnimationEnd(Animation animation)
            {
                //最后动画完成后延时100毫秒
                try
                {
                    Thread.sleep(100);
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }

                if (getData())
                    startActivity(new Intent(Welcome.this, Login.class));
                else
                    startActivity(new Intent(Welcome.this, GuidePage.class));

                //加载淡入淡出动画
                //overridePendingTransition(R.anim.alpha_in, R.anim.alpha_out);

                finish();
            }

            @Override
            public void onAnimationRepeat(Animation animation)
            {

            }
        });

    }

    /**
     * 获取数据，是否第一次打开
     * 根据版本号定，如果该存储版本号小于现在的版本号，则返回false，并更新版本号
     */
    private boolean getData()
    {
        SharedPreferences preferences = getSharedPreferences("Eda", MODE_PRIVATE);
        int version = preferences.getInt("versionCode", 0);

        if (version < versionCode)
        {
            SharedPreferences.Editor editor = getSharedPreferences("Eda", MODE_PRIVATE).edit();
            editor.putInt("versionCode", versionCode);
            editor.commit();
            return false;
        }
        else
            return true;
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        if (completeReceiver != null)
        {
            unregisterReceiver(completeReceiver);
        }
    }


    /**
     * 获取当前网络类型
     *
     * @return NO WIFI 2G 3G 4G
     */

    public String getNetworkType()
    {
        String strNetworkType = "";
        ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected())
        {
            if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI)
            {
                strNetworkType = "WIFI";
            }
            else
            {
                if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE)
                {
                    String _strSubTypeName = networkInfo.getSubtypeName();

                    // TD-SCDMA   networkType is 17
                    int networkType = networkInfo.getSubtype();
                    switch (networkType)
                    {
                        case TelephonyManager.NETWORK_TYPE_GPRS:
                        case TelephonyManager.NETWORK_TYPE_EDGE:
                        case TelephonyManager.NETWORK_TYPE_CDMA:
                        case TelephonyManager.NETWORK_TYPE_1xRTT:
                        case TelephonyManager.NETWORK_TYPE_IDEN: //api<8 : replace by 11
                            strNetworkType = "2G";
                            break;
                        case TelephonyManager.NETWORK_TYPE_UMTS:
                        case TelephonyManager.NETWORK_TYPE_EVDO_0:
                        case TelephonyManager.NETWORK_TYPE_EVDO_A:
                        case TelephonyManager.NETWORK_TYPE_HSDPA:
                        case TelephonyManager.NETWORK_TYPE_HSUPA:
                        case TelephonyManager.NETWORK_TYPE_HSPA:
                        case TelephonyManager.NETWORK_TYPE_EVDO_B: //api<9 : replace by 14
                        case TelephonyManager.NETWORK_TYPE_EHRPD:  //api<11 : replace by 12
                        case TelephonyManager.NETWORK_TYPE_HSPAP:  //api<13 : replace by 15
                            strNetworkType = "3G";
                            break;
                        case TelephonyManager.NETWORK_TYPE_LTE:    //api<11 : replace by 13
                            strNetworkType = "4G";
                            break;
                        default:
                            // http://baike.baidu.com/item/TD-SCDMA 中国移动 联通 电信 三种3G制式
                            if (_strSubTypeName.equalsIgnoreCase("TD-SCDMA") || _strSubTypeName.equalsIgnoreCase("WCDMA") || _strSubTypeName.equalsIgnoreCase("CDMA2000"))
                            {
                                strNetworkType = "3G";
                            }
                            else
                            {
                                strNetworkType = _strSubTypeName;
                            }

                            break;
                    }
                }
            }
        }
        else
        {
            strNetworkType = "NO";
        }
        return strNetworkType;
    }
}


